/**
 * Re-export of bitECS and custom wrappers. Please do not use bitECS directly!
 */

import * as bitecs from 'bitecs';
import type { Entity } from './components';
export { Types, hasComponent, defineQuery, type IWorld, type Component, addEntity, getEntityComponents, pipe, getAllEntities, removeComponent, removeEntity, entityExists, createWorld } from 'bitecs';
import { encode } from './util';

export type Entity = number;

const RefComponentName = Symbol('componentName');

export const componentName = (comp) => comp[RefComponentName];

const componentDict = new Map();

export const getComponents = () => Array.from(componentDict.entries()).map(([_, v]) => v);

export const addComponent = (world: bitecs.IWorld, comp: bitecs.Component, e: Entity, values?: Object) => {
  bitecs.addComponent(world, comp, e);
  if (values !== undefined) {
    for (let [k, v] of Object.entries(values)) {
      if (typeof v === 'string') {
        comp[k][e] = encode(v);
      } else {
        comp[k][e] = v;
      }
    }
  }
};

export const defineComponent = (name, schema) => {
  const component = bitecs.defineComponent(schema);
  component[RefComponentName] = name;
  componentDict.set(name, component);
  return component;
};

export const getComponent = (comp: string) => {
  return componentDict.get(comp);
};

// export const removeEntity = (world: IWorld, e: Entity) => {
// };
